from django.db import models
from django.contrib.auth.models import User
from iperscribo.utils import newUID
#from iperscribo.projects.models import Project




class Page(models.Model):
    uid = models.CharField(max_length=40, default=newUID, primary_key=True)
    path = models.TextField()
    owner = models.ForeignKey(User)    
    project = models.ForeignKey('projects.Project')
    creation_date = models.DateTimeField(auto_now_add=True)
    #root_revision = models.ForeignKey('Revision', related_name='root_revision')

    def __unicode__(self):
        return '%s - %s' % (self.uid, self.path) 
    
    
    
class Revision(models.Model):
    page = models.ForeignKey('Page')
    uid = models.CharField(max_length=40, default=newUID, primary_key=True)
    pid = models.IntegerField(default=-1)
    parents = models.ManyToManyField('self', related_name='children', symmetrical=False)
    #children = models.ManyToManyField('Revision')
    changes = models.TextField()
    owner = models.ForeignKey(User)
    creation_date = models.DateTimeField(auto_now_add=True)
    
    def __unicode__(self):
        return '[%05i] %s ' % (self.pid, self.uid)
    
    def save(self): 
        if not self.pid or self.pid==-1:
            "Get last value of PID from database, and increment before save"
            elements = Revision.objects.filter(page=self.page).order_by('-pid')
            if elements:
                self.pid = elements[0].pid + 1
            else:
                self.pid = 0
        super(Revision, self).save()
    
    
    
class Tag(models.Model):
    page = models.ForeignKey('Page')
    name = models.CharField(max_length=160)
    uid = models.CharField(max_length=40, default=newUID, primary_key=True)
    text = models.TextField()
    revision = models.ForeignKey('Revision')
    owner = models.ForeignKey(User)
    creation_date = models.DateTimeField(auto_now=True)
    
    def __unicode__(self):
        return '%s - %s - %s' % (self.name, self.revision.uid, self.page.path)
    
